package com.pig4cloud.pig.common.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * JSON的驼峰和下划线互转工具类
 *
 * @Author: hjl
 * @Date: 2020/11/18 17:50
 */
@Slf4j
public class JsonUtil {

	/**
	 * 将对象的大写转换为下划线加小写，例如：userName-->user_name
	 *
	 * @param object
	 * @return
	 * @throws JsonProcessingException
	 */
	public static String toUnderlineJSONString(Object object) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
		mapper.setSerializationInclusion(Include.NON_NULL);
		String reqJson = mapper.writeValueAsString(object);
		return reqJson;
	}

	/**
	 * 将下划线转换为驼峰的形式，例如：user_name-->userName
	 *
	 * @param json
	 * @param clazz
	 * @return
	 * @throws IOException
	 */
	public static <T> T toSnakeObject(String json, Class<T> clazz) throws IOException{
		ObjectMapper mapper = new ObjectMapper();
		// mapper的configure方法可以设置多种配置（例如：多字段 少字段的处理）　　　　　　
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
		T reqJson =  mapper.readValue(json, clazz);
		return reqJson;
	}

	/**
	 * 剔除掉为空或者空字符串字段
	 * @param jsonStr
	 * @return
     */
	public static Map<String, Object> parseJSON2Map(String jsonStr){
		Map<String, Object> map = new HashMap<String, Object>();
		//最外层解析
		JSONObject json = JSONObject.parseObject(jsonStr);
		try{
			for(Object k : json.keySet()){
				Object v = json.get(k);
				//如果内层还是数组的话，继续解析
				if(v instanceof JSONArray){
					List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
					Iterator<Object> it = ((JSONArray)v).iterator();
					while(it.hasNext()){
						Object object=it.next();
						if(null != object && StringUtils.isNotBlank(v.toString())){
							if(object  instanceof JSONObject){
								JSONObject json2 =(JSONObject)object;
								String jstr=	json2.toString();
								list.add(parseJSON2Map(jstr));
								map.put(k.toString(), list);
							}else{
								map.put(k.toString(), v);
							}

						}
					}
				}else {
					if(null != v && StringUtils.isNotBlank(v.toString())){
						map.put(k.toString(), v);
					}

				}
			}
		}catch (Exception e){
			log.error("parseJSON2Map is error",e);
			throw new BusinessException(11,e.getMessage());
		}

		return map;
	}

	static class DemoTest {
		private Long age;
		private String name;

		public Long getAge() {
			return age;
		}

		public void setAge(Long age) {
			this.age = age;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}

	@JsonIgnoreProperties(ignoreUnknown = true)
	static class Demo {
		private Long userId;
		private String userName;
		private Object[] demoTest;
		private Integer isCommentDisable;

		public Integer getIsCommentDisable() {
			return isCommentDisable;
		}

		public void setIsCommentDisable(Integer isCommentDisable) {
			this.isCommentDisable = isCommentDisable;
		}

		public Long getUserId() {
			return userId;
		}

		public void setUserId(Long userId) {
			this.userId = userId;
		}

		public String getUserName() {
			return userName;
		}

		public void setUserName(String userName) {
			this.userName = userName;
		}

		public Object[] getDemoTest() {
			return demoTest;
		}

		public void setDemoTest(Object[] demoTest) {
			this.demoTest = demoTest;
		}
	}

	public static void main(String[] args) throws IOException {
		Demo demo = new Demo();
		demo.setUserId(1L);
		demo.setUserName("张三");
		DemoTest demoTest=new DemoTest();
		demoTest.setAge(11L);
		Object[] dT={demoTest};
		demo.setDemoTest(dT);
		String demoStr = JsonUtil.toUnderlineJSONString(demo);
		log.info(demoStr);
		Demo demo1 = JsonUtil.toSnakeObject(demoStr, Demo.class);
		log.info(JSON.toJSONString(demo1));
		log.info("!!!!!!!!!!"+parseJSON2Map(demoStr));
		String jsonArr="{\n" +
				"\t\"generate_derived_ad\": 0,\n" +
				"\t\"track_url\": \"\",\n" +
				"\t\"abstract_list\": [],\n" +
				"\t\"ad_keywords\": [\n" +
				"\t\t\"xx\"\n" +
				"\t],\n" +
				"\t\"third_industry_id\": \"xx\",\n" +
				"\t\"is_smart_title\": 0,\n" +
				"\t\"inventory_type\": [\n" +
				"\t\t\"INVENTORY_FEED\"\n" +
				"\t],\n" +
				"\t\"source\": \"xx\",\n" +
				"\t\"scene_inventory\": null,\n" +
				"\t\"modify_time\": \"xx\",\n" +
				"\t\"ad_id\": \"xx\",\n" +
				"\t\"image_list\": [],\n" +
				"\t\"creatives\": [{\n" +
				"\t\t\"image_ids\": [\n" +
				"\t\t\t\"xx\"\n" +
				"\t\t],\n" +
				"\t\t\"creative_id\": \"xx\",\n" +
				"\t\t\"video_id\": \"xx\",\n" +
				"\t\t\"creative_word_ids\": [\n" +
				"\t\t\t\"xx\",\n" +
				"\t\t\t\"xx\"\n" +
				"\t\t],\n" +
				"\t\t\"image_id\": \"xx\",\n" +
				"\t\t\"dpa_template\": 0,\n" +
				"\t\t\"image_mode\": \"xx\",\n" +
				"\t\t\"title\": \"xx\",\n" +
				"\t\t\"derive_poster_cid\": 0\n" +
				"\t}],\n" +
				"\t\"advertiser_id\": \"xx\",\n" +
				"\t\"track_url_send_type\": \"SERVER_SEND\",\n" +
				"\t\"close_video_detail\": 0,\n" +
				"\t\"action_track_url\": \"\",\n" +
				"\t\"is_comment_disable\": 0,\n" +
				"\t\"creative_display_mode\": \"CREATIVE_DISPLAY_MODE_CTR\",\n" +
				"\t\"video_play_done_track_url\": \"\",\n" +
				"\t\"title_list\": [],\n" +
				"\t\"video_play_effective_track_url\": \"\",\n" +
				"\t\"smart_inventory\": 0,\n" +
				"\t\"video_play_track_url\": \"\",\n" +
				"\t\"promotion_card\": {\n" +
				"\t\t\"enable_store_pack\": false,\n" +
				"\t\t\"product_selling_points\": [\n" +
				"\t\t\t\"xx\"\n" +
				"\t\t],\n" +
				"\t\t\"product_description\": \"xx\",\n" +
				"\t\t\"call_to_action\": \"xx\",\n" +
				"\t\t\"enable_personal_action\": true,\n" +
				"\t\t\"product_image_id\": \"xx\"\n" +
				"\t}\n" +
				"}";
		log.info("!!!!!!!!!!"+JSONObject.parseObject(jsonArr));
		Demo demo2=JsonUtil.toSnakeObject(JSONObject.parseObject(jsonArr).toJSONString(),Demo.class);
		log.info("-----------"+JsonUtil.toSnakeObject(jsonArr,Demo.class));
		String timestamp = String.valueOf(System.currentTimeMillis()/1000);
		Integer integer= Integer.valueOf(timestamp);
		System.out.println(integer);





	}



	public static int getSecondTimestampTwo(Date date){
		if (null == date) {
			return 0;
		}
		String timestamp = String.valueOf(date.getTime()/1000);
		return Integer.valueOf(timestamp);
	}
}